package com.alipay.service.listener;

import com.alipay.exception.CustomException;
import com.alipay.exception.MqConsumeException;
import com.alipay.model.dto.TransDto;
import com.alipay.service.AccountService;
import com.alipay.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author Jun
 *
 * 监听B增加余额操作失败后，回滚A账户
 */
@Slf4j
@Service
public class TansTaskIncreaseMessageFailListener {

    @Resource
    private AccountService accountService;

    @Transactional(rollbackFor = Exception.class)
    @RabbitListener(queues = "${rabbitmq.rollback.queue}")
    protected void onMessage(String message) {

        TransDto transferDTO = JsonUtil.fromJson(message, TransDto.class);
        try {
            // 参数有效性校验
            if (transferDTO == null) {
                return;
            }

            // 回滚A的操作
            boolean flag = accountService.revertDecrease(transferDTO);

            // 非业务的异常进行重试
            if (!flag) {
                log.error("increase failed, the transId is {}", transferDTO.getTransId());
                throw new CustomException("增加余额失败，transId：" + transferDTO.getTransId());
            }
            // TODO 手动提交rabbit mq的ack确认

        } catch (Exception e) {
            log.error("message consumer failed ,  transId is {}, e={}", transferDTO.getTransId(), ExceptionUtils.getStackTrace(e));
            throw new MqConsumeException("增加余额失败，e={}", e);
        }

    }
}
